package sword;

/**
 * @Author: 海琳琦
 * @Date: 2022/6/7 14:57
 */
public class Title12 {

    int n, m, len;

    public boolean exist(char[][] board, String word) {
        n = board.length;
        m = board[0].length;
        len = word.length();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                boolean flag;
                if (board[i][j] == word.charAt(0)) {
                     flag = dfs(board, word, i, j, 0);
                    if (flag) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, String word, int i, int j, int cur) {
        if (i < 0 || i >= n || j < 0 || j >= m || board[i][j] == '1' || board[i][j] != word.charAt(cur)) {
            return false;
        }
        if (cur == len - 1) {
            return true;
        }
        char temp = board[i][j];
        board[i][j] = '1';
        boolean result;
        cur++;
        result = dfs(board, word, i - 1, j, cur) || dfs(board, word, i + 1, j, cur)
                || dfs(board, word, i, j - 1, cur) || dfs(board, word, i, j + 1, cur);
        board[i][j] = temp;
        return result;
    }

    public static void main(String[] args) {
        char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}};
        String word = "ABCCED";

    }
}
